package com.feicheng.service.impl;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.persistence.entity.Order;
import com.feicheng.persistence.model.CardTypeMain;
import com.feicheng.persistence.model.DepositRecordMain;
import com.feicheng.persistence.model.OrderMain;
import com.feicheng.persistence.model.VipMain;
import com.feicheng.persistence.service.ICardTypeService;
import com.feicheng.persistence.service.IDepositBackRequestService;
import com.feicheng.persistence.service.IDepositRecordService;
import com.feicheng.persistence.service.IOrderService;
import com.feicheng.persistence.service.IVipService;
import com.feicheng.service.BaseService;
import com.feicheng.service.IFHomeService;

@Service
public class FHomeServiceImpl extends BaseService implements IFHomeService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IDepositRecordService depositRecordService;
    
    @Autowired
    private IDepositBackRequestService epositBackRequestService;

    @Autowired
    private IVipService vipService;

    @Autowired
    private ICardTypeService cardTypeService;

    @Override
    public ResultInfo getCardAmount(Integer storeId, LocalDateTime startTime, LocalDateTime endTime, String part) {

        QueryWrapper<CardTypeMain> cardTypeQueryWrapper = new QueryWrapper<>();
        /* cailongyang delete start by 禁用的也需要进行结算 */
//        cardTypeQueryWrapper.eq(Constant.ENTITY.CARD_TYPE.D_FLG, false);
//        cardTypeQueryWrapper.eq(Constant.ENTITY.CARD_TYPE.STATU, true);
        /* cailongyang delete end by 禁用的也需要进行结算 */
        List<CardTypeMain> cardTypes = cardTypeService.getCardTypes(cardTypeQueryWrapper);

        QueryWrapper<VipMain> vipQueryWrapper = new QueryWrapper<>();
        //判断storeId是否为空
        if (null != storeId){
            vipQueryWrapper.eq(Constant.ENTITY.STORE.STORE_ID, storeId);
        }
        //判断输入订单创建时间大于等于输入开始时间
        if (null != startTime){
            vipQueryWrapper.ge(Constant.ENTITY.VIP.CT, startTime);
        }
        //判断输入订单创建时间大于等于输入结束时间
        if (null != endTime){
            vipQueryWrapper.le(Constant.ENTITY.VIP.CT, endTime);
        }

        vipQueryWrapper.eq(Constant.ENTITY.VIP.VIP_TYPE, Constant.VIP_TYPE.C);
        vipQueryWrapper.orderByAsc(Constant.ENTITY.VIP.CT);

        JSONObject cardTypeObject = new JSONObject();
        for (CardTypeMain cardTypeMain : cardTypes) {

            JSONObject cardTypeResult = new JSONObject();
            JSONArray keyArray = new JSONArray();
            cardTypeResult.put(Constant.ENTITY.CARD_TYPE.NAME, cardTypeMain.getName());
            cardTypeResult.put(Constant.ENTITY.PRICE.AMOUNT, 0);

            QueryWrapper<VipMain> cVipQueryWrapper = vipQueryWrapper.clone();

            cVipQueryWrapper.eq(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID, cardTypeMain.getCardTypeId());

            List<VipMain> vipMainList = vipService.getVips(cVipQueryWrapper);
            for (VipMain vipMain : vipMainList) {
                String key = "";
                key += vipMain.getCt().getYear();
                if ("M".equals(part) || "D".equals(part)) {
                    key += "-" + vipMain.getCt().getMonthValue();
                }
                if ("D".equals(part)) {
                    key += "-" + vipMain.getCt().getDayOfMonth();
                }

                cardTypeResult.put(Constant.ENTITY.PRICE.AMOUNT,
                        cardTypeResult.getInteger(Constant.ENTITY.PRICE.AMOUNT) + vipMain.getAmount());

                if (cardTypeResult.containsKey(key)) {
                    int amount = cardTypeResult.getInteger(key);
                    amount += vipMain.getAmount();
                    cardTypeResult.put(key, amount);
                } else {
                    keyArray.add(key);
                    cardTypeResult.put(key, vipMain.getAmount());
                }
            }
            cardTypeResult.put("keyArray", keyArray);
            cardTypeObject.put(cardTypeMain.getCardTypeId().toString() ,cardTypeResult);
        }

        return ResultInfo.success(cardTypeObject);
    }

    @Override
    public ResultInfo getOrderCount(Integer storeId, LocalDateTime startTime, LocalDateTime endTime, String part) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        //判断storeId是否为空
        if (null != storeId){
            orderQueryWrapper.eq(Constant.ENTITY.ORDER.STORE_ID,storeId);
        }
        //判断输入订单创建时间大于等于输入开始时间
        if (null != startTime){
            orderQueryWrapper.ge(Constant.ENTITY.ORDER.CT,startTime);
        }
        //判断输入订单创建时间大于等于输入结束时间
        if (null != endTime){
            orderQueryWrapper.le(Constant.ENTITY.ORDER.CT,endTime);
        }
        orderQueryWrapper.orderByAsc(Constant.ENTITY.ORDER.CT);
        //取出符合条件订单
        List<Order> orders = orderService.list(orderQueryWrapper);


        JSONObject result = new JSONObject();
        JSONArray keyArray = new JSONArray();

        for (Order order : orders) {
            String key = "";
            key += order.getCt().getYear();
            if ("M".equals(part) || "D".equals(part)) {
                key += "-" + order.getCt().getMonthValue();
            }
            if ("D".equals(part)) {
                key += "-" + order.getCt().getDayOfMonth();
            }

            if (result.containsKey(key)) {
                int count = result.getInteger(key);
                count++;
                result.remove(key);
                result.put(key, count);
            } else {
                keyArray.add(key);
                result.put(key, 1);
            }
        }

        JSONObject resultInfo = new JSONObject();
        resultInfo.put("part", result);
        resultInfo.put("keyArray", keyArray);
        resultInfo.put("count", orders.size());

        return ResultInfo.success(resultInfo);
    }

    @Override
    public ResultInfo calculateTimeMoney(Integer storeId, LocalDateTime startTime, LocalDateTime endTime, String part) {

        QueryWrapper<OrderMain> orderMainQueryWrapper = new QueryWrapper<>();
        orderMainQueryWrapper.eq(Constant.ENTITY.ORDER.D_FLG,false);
        orderMainQueryWrapper.eq(Constant.ENTITY.CONSUME_RECORD.TYPE,Constant.MODEL_NAME.Order.P);
        // 如果sotreId不为空 加入检索条件
        if (null != storeId) {
            orderMainQueryWrapper.eq(Constant.ENTITY.ORDER.STORE_ID, storeId);
        }
        // 如果开始时间不为空 加入检索条件
        if (null != startTime) {
            orderMainQueryWrapper.ge(Constant.ENTITY.PAYMENT_RECORD.CT, startTime);
        }
        // 如果结束时间不为空 加入检索条件
        if (null != endTime) {
            orderMainQueryWrapper.le(Constant.ENTITY.PAYMENT_RECORD.CT, endTime);
        }

        // 取得类型为支付的订单
        List<OrderMain> payOrder = orderService.getCalculateTimeMoney(orderMainQueryWrapper);

        JSONObject result = new JSONObject();
        JSONArray keyArray = new JSONArray();

        Integer total = 0;
        for (OrderMain order : payOrder) {
            String key = "";
            key += order.getCt().getYear();
            if ("M".equals(part) || "D".equals(part)) {
                key += "-" + order.getCt().getMonthValue();
            }
            if ("D".equals(part)) {
                key += "-" + order.getCt().getDayOfMonth();
            }

            if (result.containsKey(key)) {
                int amount = result.getInteger(key);
                amount += order.getAmount();
                result.put(key, amount);
            } else {
                keyArray.add(key);
                result.put(key, order.getAmount());
            }
            total += order.getAmount();
        }

        JSONObject resultInfo = new JSONObject();
        resultInfo.put("part", result);
        resultInfo.put("keyArray", keyArray);
        resultInfo.put("amount", total);

        return ResultInfo.success(resultInfo);

    }

    /**
     * 查询押金支付金额
     * @return
     */
    @Override
    public ResultInfo getDepositAmount(Integer storeId, LocalDateTime startTime, LocalDateTime endTime, String part) {

        QueryWrapper<DepositRecordMain> depositRecordMainQueryWrapper = new QueryWrapper<>();
//        depositRecordMainQueryWrapper.eq(Constant.ENTITY.CLIENT_DEPOSIT.STATU, Constant.VAL.BACK_REQUEST_DEPOSIT.PAY);
        if (null != storeId){
            depositRecordMainQueryWrapper.eq(Constant.ENTITY.STORE.STORE_ID, storeId);
        }

        // 如果开始时间不为空 加入检索条件
        if (null != startTime) {
            depositRecordMainQueryWrapper.ge(Constant.ENTITY.DEPOSIT_RECORD.CT, startTime);
        }
        // 如果结束时间不为空 加入检索条件
        if (null != endTime) {
            depositRecordMainQueryWrapper.le(Constant.ENTITY.DEPOSIT_RECORD.CT, endTime);
        }
        depositRecordMainQueryWrapper.eq("pay_flg", 1);
        depositRecordMainQueryWrapper.eq("statu", "PAY");
        
        

        List<DepositRecordMain> depositRecordMains =
            depositRecordService.searchWithPayment(depositRecordMainQueryWrapper);

        JSONObject result = new JSONObject();
        JSONArray keyArray = new JSONArray();

        Integer total = 0;
        for (DepositRecordMain order : depositRecordMains) {
            String key = "";
            key += order.getCt().getYear();
            if ("M".equals(part) || "D".equals(part)) {
                key += "-" + order.getCt().getMonthValue();
            }
            if ("D".equals(part)) {
                key += "-" + order.getCt().getDayOfMonth();
            }

            if (result.containsKey(key)) {
                int amount = result.getInteger(key);
                amount += order.getAmount();
                result.put(key, amount);
            } else {
                keyArray.add(key);
                result.put(key, order.getAmount());
            }
            total += order.getAmount();
        }

        JSONObject resultInfo = new JSONObject();
        resultInfo.put("part", result);
        resultInfo.put("keyArray", keyArray);
        resultInfo.put("amount", total);

        return ResultInfo.success(resultInfo);
    }

    /**
     * 查询押金申退金额
     * @see com.feicheng.service.IFHomeService#getDepositBackAmount
     */
    @Override
    public ResultInfo getDepositBackAmount(Integer storeId, LocalDateTime startTime, LocalDateTime endTime, String part) {
    	
//    	QueryWrapper<DepositBackRequest> dbrWrapper = new QueryWrapper<>();
//    	dbrWrapper.eq(Constant.ENTITY.DEPOSIT_BACK_REQUEST.STATU, Constant.VAL.BACK_REQUEST_DEPOSIT.BCK);
//		if (null != storeId) {
//			dbrWrapper.eq(Constant.ENTITY.DEPOSIT_BACK_REQUEST.STORE_ID, storeId);
//		}
//		
//		// 如果开始时间不为空 加入检索条件
//		if (null != startTime) {
//			dbrWrapper.ge(Constant.ENTITY.DEPOSIT_BACK_REQUEST.CT, startTime);
//		}
//		// 如果结束时间不为空 加入检索条件
//		if (null != endTime) {
//			dbrWrapper.le(Constant.ENTITY.DEPOSIT_BACK_REQUEST.CT, endTime);
//		}
//		
//		List<DepositBackRequest> depositBackRequests = this.epositBackRequestService.list(dbrWrapper);
//		
//		JSONObject result = new JSONObject();
//		JSONArray keyArray = new JSONArray();
//
//		Integer total = 0;
//		for (DepositBackRequest order : depositBackRequests) {
//			String key = "";
//			key += order.getCt().getYear();
//			if ("M".equals(part) || "D".equals(part)) {
//				key += "-" + order.getCt().getMonthValue();
//			}
//			if ("D".equals(part)) {
//				key += "-" + order.getCt().getDayOfMonth();
//			}
//
//			if (result.containsKey(key)) {
//				int amount = result.getInteger(key);
//				amount += order.getAmount();
//				result.put(key, amount);
//			} else {
//				keyArray.add(key);
//				result.put(key, order.getAmount());
//			}
//			total += order.getAmount();
//		}
//
//		JSONObject resultInfo = new JSONObject();
//		resultInfo.put("part", result);
//		resultInfo.put("keyArray", keyArray);
//		resultInfo.put("amount", total);
//
//		return ResultInfo.success(resultInfo);
    	
        QueryWrapper<DepositRecordMain> depositRecordMainQueryWrapper = new QueryWrapper<>();
        depositRecordMainQueryWrapper.eq(Constant.ENTITY.CLIENT_DEPOSIT.STATU, Constant.VAL.BACK_REQUEST_DEPOSIT.BCK);
        if (null != storeId){
            depositRecordMainQueryWrapper.eq(Constant.ENTITY.STORE.STORE_ID, storeId);
        }

        // 如果开始时间不为空 加入检索条件
        if (null != startTime) {
            depositRecordMainQueryWrapper.ge(Constant.ENTITY.DEPOSIT_RECORD.CT, startTime);
        }
        // 如果结束时间不为空 加入检索条件
        if (null != endTime) {
            depositRecordMainQueryWrapper.le(Constant.ENTITY.DEPOSIT_RECORD.CT, endTime);
        }

        List<DepositRecordMain> depositRecordMains =
                depositRecordService.searchWithPayment(depositRecordMainQueryWrapper);

        JSONObject result = new JSONObject();
        JSONArray keyArray = new JSONArray();

        Integer total = 0;
        for (DepositRecordMain order : depositRecordMains) {
            String key = "";
            key += order.getCt().getYear();
            if ("M".equals(part) || "D".equals(part)) {
                key += "-" + order.getCt().getMonthValue();
            }
            if ("D".equals(part)) {
                key += "-" + order.getCt().getDayOfMonth();
            }

            if (result.containsKey(key)) {
                int amount = result.getInteger(key);
                amount += order.getAmount();
                result.put(key, amount);
            } else {
                keyArray.add(key);
                result.put(key, order.getAmount());
            }
            total += order.getAmount();
        }

        JSONObject resultInfo = new JSONObject();
        resultInfo.put("part", result);
        resultInfo.put("keyArray", keyArray);
        resultInfo.put("amount", total);

        return ResultInfo.success(resultInfo);
    }

    /**
     * 根据会员卡类型查总金额
     * @param param
     * @return
     */
    @Override
    public ResultInfo getAmount(JSONObject param) {

        //根据会员创建时间区间进行查询

        LocalDateTime ct = (LocalDateTime) param.get(Constant.ENTITY.VIP.CT);
        LocalDateTime lastct = (LocalDateTime) param.get(Constant.HTTP.PARAM.LASTCT);
        Map<String,Integer> amount = new LinkedHashMap<>();

        if(ct.getYear() == lastct.getYear() && ct.getMonthValue() == lastct.getMonthValue()){
            QueryWrapper<VipMain> queryWrapper = new QueryWrapper<VipMain>();
            queryWrapper.isNotNull(Constant.ENTITY.VIP.CARD_RECORD_ID);
            if (null !=param.getInteger(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID)) {
                queryWrapper.eq(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID,param.getInteger(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID));
            }
            if (StringUtils.hasLength( param.getString(Constant.ENTITY.STORE.STORE_ID))) {
                queryWrapper.eq(Constant.ENTITY.STORE.STORE_ID,param.getString(Constant.ENTITY.STORE.STORE_ID));
            }
            queryWrapper.ge(Constant.ENTITY.VIP.CT,ct);
            queryWrapper.le(Constant.ENTITY.VIP.CT,lastct);
            amount.put(ct.toString(), vipService.getAmount(queryWrapper));
        }else {
            while (!(ct.getYear() == lastct.getYear() && ct.getMonthValue() == lastct.getMonthValue())) {
                QueryWrapper<VipMain> queryWrapper = new QueryWrapper<VipMain>();
                queryWrapper.isNotNull(Constant.ENTITY.VIP.CARD_RECORD_ID);
                if (null !=param.getInteger(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID)) {
                    queryWrapper.eq(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID,param.getInteger(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID));
                }
                if (StringUtils.hasLength( param.getString(Constant.ENTITY.STORE.STORE_ID))) {
                    queryWrapper.eq(Constant.ENTITY.STORE.STORE_ID,param.getString(Constant.ENTITY.STORE.STORE_ID));
                }
                LocalDateTime oldCt = ct;
                queryWrapper.ge(Constant.ENTITY.VIP.CT,ct);
                ct = ct.plusMonths(1);
                ct = LocalDateTime.of(ct.getYear() , ct.getMonth() , 1 ,0,0,0 );
//            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            String localTimeCt = df.format(ct);
//            StringBuffer Ct = new StringBuffer(localTimeCt);
//
//            Ct.replace(8,17,"01 00:00:00");
//            LocalDateTime ldt = LocalDateTime.parse(Ct,df);
                queryWrapper.le(Constant.ENTITY.DEPOSIT_RECORD.CT,ct);
                amount.put(oldCt.toString(), vipService.getAmount(queryWrapper));
            }
            //最后一个月时间
            QueryWrapper<VipMain> queryWrapper = new QueryWrapper<VipMain>();
            queryWrapper.isNotNull(Constant.ENTITY.VIP.CARD_RECORD_ID);
            if (null !=param.getInteger(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID)) {
                queryWrapper.eq(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID,param.getInteger(Constant.ENTITY.CARD_TYPE.CARD_TYPE_ID));
            }
            if (StringUtils.hasLength( param.getString(Constant.ENTITY.STORE.STORE_ID))) {
                queryWrapper.eq(Constant.ENTITY.STORE.STORE_ID,param.getString(Constant.ENTITY.STORE.STORE_ID));
            }
            queryWrapper.ge(Constant.ENTITY.VIP.CT,ct);
            queryWrapper.le(Constant.ENTITY.VIP.CT,lastct);
            amount.put(ct.toString(), vipService.getAmount(queryWrapper));
        }
        return ResultInfo.success(amount);
    }


}
